<script setup>
import { ref, reactive, onMounted, h } from 'vue';
import { BookService } from '../services/BookService';
import BookDetail from './BookDetail.vue';
import { NButton, NIcon } from 'naive-ui';
import { 
  Search, 
  BookOutline, 
  PersonOutline, 
  BusinessOutline, 
  EyeOutline
} from '@vicons/ionicons5';

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  pageCount: 0
});

// 搜索参数
const searchParams = reactive({
  title: '',
  author: '',
  publisher: '',
  keyword: ''
});

// 搜索模式
const searchMode = ref('normal'); // normal 或 fulltext

// 搜索结果
const books = ref([]);
const loading = ref(false);
const message = window.$message;

// 图书详情
const detailVisible = ref(false);
const selectedIsbn = ref('');

// 打开图书详情
const openBookDetail = (row) => {
  selectedIsbn.value = row.isbn;
  detailVisible.value = true;
};

// 定义表格列
const columns = ref([
  { title: 'ISBN', key: 'isbn' },
  { title: '书名', key: 'title' },
  { title: '作者', key: 'author' },
  { title: '出版社', key: 'publisher' },
  { title: '出版年份', key: 'publicationDate' },
  { title: '主题', key: 'subject' },
  { title: '馆藏位置', key: 'currentLocation' },
  { 
    title: '操作', 
    key: 'actions',
    render(row) {
      return h(
        'div',
        {
          style: 'display: flex; gap: 8px; justify-content: center;'
        },
        [
          h(
            NButton,
            {
              size: 'small',
              quaternary: true,
              onClick: () => openBookDetail(row)
            },
            { default: () => '查看', icon: () => h(NIcon, null, { default: () => h(EyeOutline) }) }
          )
        ]
      )
    }
  }
]);

// 搜索方法
const searchBooks = async () => {
  loading.value = true;
  try {
    if (searchMode.value === 'fulltext' && searchParams.keyword) {      // 全文搜索
      const params = {
        keyword: searchParams.keyword,
        page: pagination.page,
        size: pagination.pageSize
      };
      const result = await BookService.searchByFullText(params);
      books.value = result.records;
      pagination.itemCount = result.total;
      pagination.pageCount = result.pages; // 添加总页数
    } else {      // 普通搜索
      const params = {
        page: pagination.page,
        size: pagination.pageSize,
        title: searchParams.title || undefined,
        author: searchParams.author || undefined,
        publisher: searchParams.publisher || undefined
      };
      const result = await BookService.searchBooks(params);
      books.value = result.records;
      pagination.itemCount = result.total;
      pagination.pageCount = result.pages; // 添加总页数
    }
  } catch (error) {
    console.error('搜索图书失败:', error);
    if (message) {
      message.error('搜索图书失败: ' + error);
    }
  } finally {
    loading.value = false;
  }
};

// 页码变化处理
const handlePageChange = (currentPage) => {
  pagination.page = currentPage;
  searchBooks();
};

// 页大小变化处理
const handlePageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.page = 1;
  searchBooks();
};

// 切换搜索模式
const toggleSearchMode = () => {
  searchMode.value = searchMode.value === 'normal' ? 'fulltext' : 'normal';
  // 清空之前的搜索参数
  if (searchMode.value === 'normal') {
    searchParams.keyword = '';
  } else {
    searchParams.title = '';
    searchParams.author = '';
    searchParams.publisher = '';
  }
  pagination.page = 1;
};

// 重置搜索条件
const resetSearch = () => {
  searchParams.title = '';
  searchParams.author = '';
  searchParams.publisher = '';
  searchParams.keyword = '';
  pagination.page = 1;
};

// 初始化加载数据
onMounted(() => {
  // searchBooks();
});
</script>

<template>
  <div class="book-index">
    <n-card title="图书索引系统" class="search-card">
      <n-space vertical>
        <n-radio-group v-model:value="searchMode" name="searchMode">
          <n-radio-button value="normal">多条件搜索</n-radio-button>
          <n-radio-button value="fulltext">全文搜索</n-radio-button>
        </n-radio-group>

        <template v-if="searchMode === 'normal'">
          <n-form :model="searchParams" label-placement="left" label-width="auto" require-mark-placement="right-hanging">
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="8" label="书名">
                <n-input v-model:value="searchParams.title" placeholder="请输入书名关键字">
                  <template #prefix>
                    <n-icon :component="BookOutline" />
                  </template>
                </n-input>
              </n-form-item-gi>
              <n-form-item-gi :span="8" label="作者">
                <n-input v-model:value="searchParams.author" placeholder="请输入作者关键字">
                  <template #prefix>
                    <n-icon :component="PersonOutline" />
                  </template>
                </n-input>
              </n-form-item-gi>
              <n-form-item-gi :span="8" label="出版社">
                <n-input v-model:value="searchParams.publisher" placeholder="请输入出版社关键字">
                  <template #prefix>
                    <n-icon :component="BusinessOutline" />
                  </template>
                </n-input>
              </n-form-item-gi>
            </n-grid>
          </n-form>
        </template>

        <template v-else>
          <n-input 
            v-model:value="searchParams.keyword" 
            placeholder="请输入搜索关键词" 
            clearable
          >
            <template #prefix>
              <n-icon :component="Search" />
            </template>
          </n-input>
        </template>

        <n-space justify="end">
          <n-button @click="resetSearch" quaternary>重置</n-button>
          <n-button @click="searchBooks" type="primary" :loading="loading">搜索</n-button>
        </n-space>
      </n-space>
    </n-card>    <n-card title="搜索结果" class="result-card">
      <n-spin :show="loading">        <n-data-table
          :columns="columns"
          :data="books"
          :pagination="{
            page: pagination.page,
            pageSize: pagination.pageSize,
            itemCount: pagination.itemCount,
            pageCount: pagination.pageCount,
            onChange: handlePageChange,
            onPageSizeChange: handlePageSizeChange,
            pageSizes: [10, 20, 50, 100]
          }"
          :bordered="false"          :striped="true"
        />
      </n-spin>    </n-card>

    <!-- 图书详情抽屉 -->
    <book-detail
      :show="detailVisible"
      @update:show="detailVisible = $event"
      :isbn="selectedIsbn"
    />
  </div>
</template>

<style scoped>
.book-index {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.result-card {
  min-height: 400px;
}
</style>
